package com.cz.ssyx.home.service.impl;

import com.cz.ssyx.client.product.ProductFeignClient;
import com.cz.ssyx.client.search.SkuFeignClient;
import com.cz.ssyx.client.user.UserFeignClient;
import com.cz.ssyx.home.service.HomeService;
import com.cz.ssyx.model.product.Category;
import com.cz.ssyx.model.product.SkuInfo;
import com.cz.ssyx.model.search.SkuEs;
import com.cz.ssyx.vo.user.LeaderAddressVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @descriptions:
 * @author: Joker.
 * @date: 2024/4/24 23:32
 * @version: 1.0
 */
@Service
public class HomeServiceImpl implements HomeService {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private SkuFeignClient skuFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    //返回首页数据
    @Override
    public Map<String, Object> homeData(Long userId) {
        HashMap<String, Object> map = new HashMap<>();

        CompletableFuture<Void> leaderAddressCompletableFuture = CompletableFuture.runAsync(() -> {
            //1.远程调用获取提货点和团长信息
            LeaderAddressVo leaderAddressVo = userFeignClient
                    .getUserAddressByUserId(userId);
            map.put("leaderAddressVo", leaderAddressVo);
        }, threadPoolExecutor);

        CompletableFuture<Void> allCategoryCompletableFuture = CompletableFuture.runAsync(() -> {
            //2.远程调用获取全部的商品分类信息
            List<Category> allCategoryList = productFeignClient.findAllCategoryList();
            map.put("categoryList", allCategoryList);
        }, threadPoolExecutor);

        CompletableFuture<Void> newPersonCompletableFuture = CompletableFuture.runAsync(() -> {
            //3.获取新人专享商品
            List<SkuInfo> newPersonSkuInfoList = productFeignClient.findNewPersonSkuInfoList();
            map.put("newPersonSkuInfoList", newPersonSkuInfoList);
        }, threadPoolExecutor);

        CompletableFuture<Void> hotSkuCompletableFuture = CompletableFuture.runAsync(() -> {
            //4.获取爆款商品，调用search
            List<SkuEs> hotSkuList = skuFeignClient.findHotSkuList();
            map.put("hotSkuList", hotSkuList);
        }, threadPoolExecutor);

        //每个线程都完成后 提交
        CompletableFuture.allOf(leaderAddressCompletableFuture,
                                allCategoryCompletableFuture,
                                newPersonCompletableFuture,
                                hotSkuCompletableFuture).join();

        return map;
    }
}
